<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>

    <el-card>
      <el-alert
        title="注意：只允许为第三级分类设置相关参数"
        type="warning"
        show-icon
        :closable="false"
      >
      </el-alert>

      <el-row>
        <el-col :span="3">
          <span>选择商品分类：</span>
        </el-col>
        <el-col :span="6">
          <el-cascader
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            size="small"
            :clearable="true"
            @change="parentCateChanged"
          ></el-cascader>
        </el-col>
      </el-row>

      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="dialogAddForm = true"
            >添加参数</el-button
          >
          <el-table :data="manyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(attr_val, index) in scope.row.attr_vals"
                  :key="index"
                  @close="removeVal(index,scope.row)"
                  >{{ attr_val }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="参数名称"
            ></el-table-column>
            <el-table-column label="操作" width="285px">
              <template slot-scope="scoap">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scoap.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scoap.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态属性" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="dialogAddForm = true"
            >添加属性</el-button
          >
          <el-table :data="onlyTableData" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  closable
                  v-for="(attr_val, index) in scope.row.attr_vals"
                  :key="index"
                  @close="removeVal(index,scope.row)"
                  >{{ attr_val }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ 添加</el-button
                >
              </template>
            </el-table-column>
            <el-table-column type="index" label="#"></el-table-column>
            <el-table-column
              prop="attr_name"
              label="属性名称"
            ></el-table-column>
            <el-table-column label="操作" width="285px">
              <template slot-scope="scoap">
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  size="mini"
                  @click="showEditDialog(scoap.row)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  size="mini"
                  @click="deleteParams(scoap.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>

      <el-dialog
        :title="'添加' + titleText"
        :visible.sync="dialogAddForm"
        width="30%"
        @close="addDialogClosed()"
      >
        <el-form :model="addForm" :rules="addFormRoles" ref="addFormRef">
          <el-form-item :label="titleText + '名称'" prop="attr_name">
            <el-input v-model="addForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogAddForm = false">取 消</el-button>
          <el-button type="primary" @click="addParams()">确 定</el-button>
        </div>
      </el-dialog>

      <el-dialog
        :title="'修改' + titleText"
        :visible.sync="dialogEditForm"
        width="30%"
        @close="editDialogClosed()"
      >
        <el-form :model="editForm" :rules="addFormRoles" ref="editFormRef">
          <el-form-item :label="titleText + '名称'" prop="attr_name">
            <el-input v-model="editForm.attr_name"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogEditForm = false">取 消</el-button>
          <el-button type="primary" @click="editParams()">确 定</el-button>
        </div>
      </el-dialog>
    </el-card>
  </div>
</template>

<script>
export default {
  data() {
    return {
      parentCateList: [],
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
        expandTrigger: 'hover',
      },
      selectedKeys: [],
      activeName: 'many',
      manyTableData: [],
      onlyTableData: [],
      dialogAddForm: false,
      dialogEditForm: false,
      addForm: {
        attr_name: '',
      },
      editForm: {
        attr_id: '',
        attr_name: '',
      },
      addFormRoles: {
        attr_name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
      },
    }
  },
  created() {
    this.getParentCateList()
  },
  methods: {
    async getParentCateList() {
      const { data: res } = await this.$http.get('categories', {
        params: { type: 3 },
      })

      if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

      this.parentCateList = res.data
    },
    parentCateChanged() {
      if (this.selectedKeys.length < 3) {
        this.selectedKeys = []
        this.manyTableData= []
        this.onlyTableData= []
        return
      }

      this.getParamsList()
    },
    handleTabClick(tab, event) {
      //console.log(tab, event);
      this.getParamsList()
    },
    async getParamsList() {
      if (this.selectedKeys.length === 3) {
        const { data: res } = await this.$http.get(
          `categories/${this.cateId}/attributes`,
          { params: { sel: this.activeName } }
        )

        if (res.meta.status !== 200) return this.$message.error(res.meta.msg)

        res.data.forEach((item) => {
          item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
          item.inputVisible = false
          item.inputValue = ''
        })

        if (this.activeName === 'many') {
          this.manyTableData = res.data
        } else {
          this.onlyTableData = res.data
        }
      }
    },
    addDialogClosed() {
      this.$refs.addFormRef.resetFields()
      this.dialogAddForm = false
    },
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
      this.dialogEditForm = false
    },
    async addParams() {
      this.$refs.addFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.post(
          `categories/${this.cateId}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 201) return this.$message.error('添加失败!')

        this.addDialogClosed()

        this.getParamsList()
        this.$message.success('添加成功!')
      })
    },
    showEditDialog(paramInfo) {
      this.editForm = paramInfo
      this.dialogEditForm = true
    },
    async editParams() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return

        const { data: res } = await this.$http.put(
          `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
          {
            attr_name: this.editForm.attr_name,
            attr_sel: this.activeName,
          }
        )

        if (res.meta.status !== 200) return this.$message.error('修改失败!')

        this.editDialogClosed()

        this.getParamsList()
        this.$message.success('修改成功!')
      })
    },
    deleteParams(id) {
      this.$confirm('确认删除吗?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
        .then(async () => {
          const { data: res } = await this.$http.delete(
            `categories/${this.cateId}/attributes/${id}`
          )

          if (res.meta.status !== 200)
            return this.$message.error('删除分类失败!')

          this.getParamsList()

          this.$message.success('删除分类成功!')
        })
        .catch(() => {})
    },
    async handleInputConfirm(row) {
        if(row.inputValue.trim().length > 0){
            const { data: res } = await this.$http.put(
                `categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ') ? 
                        row.attr_vals.join(' ')+' '+row.inputValue.trim() : 
                        row.inputValue.trim()
                }
            )

            if (res.meta.status !== 200) return this.$message.error('添加失败!')

            row.attr_vals.push(row.inputValue.trim())
            this.$message.success('添加成功!')
        }

        row.inputVisible = false
        row.inputValue = ''
    },
    async removeVal(index,row){

        row.attr_vals.splice(index,1)

        const { data: res } = await this.$http.put(
                `categories/${this.cateId}/attributes/${row.attr_id}`,
                {
                    attr_name: row.attr_name,
                    attr_sel: row.attr_sel,
                    attr_vals: row.attr_vals.join(' ')
                }
            )

            if (res.meta.status !== 200) return this.$message.error('删除失败!')

            this.$message.success('删除成功!')
    },
    showInput(row) {
      row.inputVisible = true

      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
  },
  computed: {
    isBtnDisable() {
      if (this.selectedKeys.length !== 3) return true
      else return false
    },
    cateId() {
      if (this.selectedKeys.length === 3) {
        return this.selectedKeys[this.selectedKeys.length - 1]
      }

      return null
    },
    titleText() {
      if (this.activeName === 'many') return '动态参数'
      else return '静态属性'
    },
  },
}
</script>

<style lang="less" scoped>
.el-tag {
  margin: 0 5px 5px 0;
}
.input-new-tag {
  width: 90px;
  margin-left: 10px;
  vertical-align: bottom;
}
.el-button {
  margin-left: 5px;
}
</style>